<template>
  <div class="detail-main">
    <!-- 卡片 -->
    <el-card shadow="never" style="margin: 30px;">
      <div slot="header">
        <span>{{ article.id? '编辑文章':'新增文章' }}</span>
      </div>
      <!-- 表单 -->
      <el-form ref="form" :model="article" :rules="rules" label-width="80px" :inline="false" size="normal">
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="标题" prop="title">
              <el-input v-model="article.title" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="作者" prop="author">
              <el-input v-model="article.author" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="是否显示">
              <el-switch
                v-model="article.isShow"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="文章概要">
          <el-input
            v-model="article.summary"
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            ref="uploadCoverImg"
            class="upload-demo"
            :headers="{token}"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            action="/lejuAdmin/material/uploadFileOss"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <img v-if="article.coverImg" class="cover-img" :src="article.coverImg" alt="">
          <el-button v-if="article.coverImg" type="text" style="color:red" size="mini" @click="removeCoverImg">删除</el-button>

        </el-form-item>
        <el-form-item label="文章内容">
          <Tinymce v-model="tinContent" :height="400" />
        </el-form-item>
        <el-form-item label="文章内容2">
          <MarkdownEditor ref="markdownEditor" v-model="mdContent" class="markdown-editor" />
          <el-button type="primary" size="small" @click="getMarkdownContent">获取内容</el-button>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSave">立即保存</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>

    </el-card>

  </div>
</template>

<script>
import { getToken } from '@/utils/myAuth'
import Tinymce from '@/components/Tinymce'
import { addArticle as addArticleApi,
  productArticle as productArticleApi,
  updateArticle as updateArticleApi } from '@/api/content/article'
import MarkdownEditor from '@/components/MarkdownEditor'
export default {
  components: {
    Tinymce,
    MarkdownEditor
  },
  data() {
    return {
      article: {
        isShow: 1, // 默认值
        coverImg: 'https://bufan-apitown.oss-cn-beijing.aliyuncs.com/bftec/2021080410225605920171229174118.jpg'
      }, // 表单的数据对象
      tinContent: '<p style="color:red">今天天气不错</p>', // 富文本内容\
      mdContent: '# markdown使用', // 这是markdown初始化内容
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '作者不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    token() {
      return getToken()
    }
  },
  created() {
    this.article.id = this.$route.params.id
    // console.log('id', this.$route.params.id)
    // 如果是有id,说明是编辑功能
    if (this.article.id) {
      this.getArticle()
    }
  },
  mounted() {

  },
  methods: {
    // 执行提交
    doSave() {
      // 集成富文本内容 对富文本来说,接口的content1和content2都是转换后的html内容
      this.article.content1 = this.tinContent
      this.article.content2 = this.tinContent
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 需要根据情况判断是更新还是新增!!
          // var api
          // if (this.article.id) {
          //   api = updateArticleApi
          // } else {
          //   api = addArticleApi
          // }
          var api = this.article.id ? updateArticleApi : addArticleApi
          api(this.article)
            .then(res => {
              const { success, message: errMsg } = res
              if (success) {
                this.$message.success('提交成功!')
                this.$router.push({ name: 'contentArticle' })
              } else {
                this.$message.error(errMsg)
              }
            })
        } else {
          this.$message.error('请注意表单验证!')
          return false
        }
      })
    },
    // 根据id获取文章明细
    getArticle() {
      productArticleApi(this.article.id)
        .then(res => {
          const { success, data, message: errMsg } = res
          if (success) {
            const { productArticle } = data
            this.article = productArticle
            // 针对富文本手动处理
            this.tinContent = this.article.content1
          } else {
            this.$message.error(errMsg)
          }
        })
    },
    // 上传成功的回调
    handleSuccess(response, file, fileList) {
      const { success, data, message: errMsg } = response
      if (success) {
        const { fileUrl } = data
        this.$message.success('上传成功!')
        // https://bufan-apitown.oss-cn-beijing.aliyuncs.com/bftec/2021080410225605920171229174118.jpg
        console.log(fileUrl)
        // 赋值
        this.article.coverImg = fileUrl
        // 清除上传列表
        this.$refs.uploadCoverImg.clearFiles()
      } else {
        this.$message.error(errMsg)
      }
    },
    // 上传类型判断
    beforeUpload(file) {
      // 正则表达式
      var reg = /image\/(jpeg|png|jpg)/g
      const isImg = reg.test(file.type)
      const isLt2M = file.size / 1024 / 1024 < 1.5
      if (!isImg) {
        this.$message.error('只能上传图片格式')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过1.5MB!')
      }
      return isImg && isLt2M
    },
    // 删除图片
    removeCoverImg() {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 只用执行本地删除
        this.article.coverImg = ''
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {

      })
    },
    // 测试获取markdown内容
    getMarkdownContent() {
      // 能不能响应
      console.log('mdContent', this.mdContent)
      // 利用api再获取
      var editor = this.$refs.markdownEditor
      console.log('getValue', editor.getValue())
      console.log('getHtml', editor.getHtml())
    }
  }
}
</script>

<style scoped lang="scss">
  .detail-main{
    .cover-img{
      width: 200px;
      height: 100px;
    }
    // 如果在组件外部 修改组件内部的样式,因为样式加了scope导致解析不是原来的classname,所以我们需要样式穿透
    // bug # https://github.com/nhn/tui.editor/issues/1152
    // # https://github.com/nhn/tui.editor/issues/923
    .markdown-editor{
      ::v-deep .tui-editor .te-md-splitter{
          width: 50%;
      }

    }
  }
</style>
